﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MVC_Project.Model;
using MVC_Project.Dal.Goods;

namespace MVC_Project.Bll.Goods
{
    public class GoodsBll : BaseBll<Good>
    {
        public override void SetDal()
        {
            Dal = new GoodsDal();
        }

        public List<Good> GetGoodsPage(int page, int size, string name, out int count)
        {
            var users = Dal.Query();

            if (!string.IsNullOrWhiteSpace(name))
            {
                users = users.Where(u => u.name.Contains(name));
            }

            count = users.Count();

            var list = users.OrderBy(u => u.id).Skip((page - 1) * size).Take(size).ToList();

            return list;
        }

        public Good GetGoodsById(int id)
        {
            return Dal.Query().Where(u => u.id == id).FirstOrDefault();
        }

        public int UpdateGoods(Good good) {

            var data = Dal.Query().Where(g => g.id == good.id).FirstOrDefault();
            //先查询属性和属性值 表 
            var goodkey = data.GoodPropertyKey;
            var goodkeyvalue = new List<GoodPropertyValue>();
            foreach (var key in goodkey)
            {
                goodkeyvalue.AddRange(key.GoodPropertyValue);
            }
            GoodPropertyKeyDal kdal = new GoodPropertyKeyDal();
            GoodPropertyValueDal vdal = new GoodPropertyValueDal();

            //先删除再添加新的数据
            vdal.Delete(goodkeyvalue);
            kdal.Delete(goodkey.ToList());
            kdal.Add(good.GoodPropertyKey.ToList());

            //更新商品
            Dal.Update(good);

            return Dal.SaveChanges();
        }
    }
}
